package com.locationhistory.activity;

import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.locationhistory.R;
import com.locationhistory.bean.LocationHistory;
import com.locationhistory.dao.LocationDAO;
import com.locationhistory.dao.impl.LocationDAOImpl;
import com.locationhistory.net.HttpNetService;
import com.locationhistory.parse.JsonParser;
import com.locationhistory.ui.LocationHistoryAdapter;
import com.locationhistory.utils.CommonUtils;
import com.locationhistory.utils.Constants;
import com.locationhistory.utils.Logger;

/**
 * 
 * @author thuanlv1
 * 
 */
public class MainActivity extends BaseActivity {
	private ListView listView;
	private List<LocationHistory> locationHistoryList;

	public static boolean running = true;

	private LocationDAO locationDAO;
	private static LocationManager locManager;
	private static LocationListener locListener;
	private static Location mobileLocation;
	private LocationHistory dbLocation;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// run thread get location

		// init LocationDAO
		LocationDAO locationDAO = new LocationDAOImpl(this);
		// get List View
		listView = (ListView) findViewById(R.id.listView);

		// get location history
		locationHistoryList = locationDAO.getLocationList();
		Logger.debug(locationHistoryList.toString());

		// put to list
		LocationHistoryAdapter adapter = new LocationHistoryAdapter(this, locationHistoryList);
		listView.setAdapter(adapter);
		
		getLocation();
		Logger.debug("Address: " + getAddress());
		
		showDialog("Current Location", getAddress(), false);
		
		//handlerGetLocation.sendEmptyMessageDelayed(1, 10000);

		// catch button event onlick
		Button button = (Button) findViewById(R.id.settingButton);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						SettingActivity.class);

				startActivity(intent);
			}
		});
	}

	Handler handlerGetLocation = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			getLocation();
			String address = getAddress();
			locationDAO = new LocationDAOImpl(MainActivity.this);

			dbLocation = locationDAO.getLocationByAddress(address);
			if (dbLocation == null) {
				// insert new location
				dbLocation = new LocationHistory();
				dbLocation.setLocation(address);
				dbLocation.setUpdatedTime(CommonUtils.convertFromDateToString(
						new Date(System.currentTimeMillis()),
						Constants.Date.MMDDYYYYHHMMSS_PATTERN));

				locationDAO.saveLocation(dbLocation);
			}
			
			handlerGetLocation.sendEmptyMessageDelayed(1, 10000);
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/**
	 * get current location base one Network and user's location.
	 * 
	 */
	private void getLocation() {
		locManager = (LocationManager) MainActivity.this
				.getSystemService(Context.LOCATION_SERVICE);
		locListener = new LocationListener() {
			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			@Override
			public void onProviderEnabled(String provider) {
			}

			@Override
			public void onProviderDisabled(String provider) {
			}

			@Override
			public void onLocationChanged(Location location) {
				mobileLocation = location;
			}
		};

		locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
				0, locListener);
	} // End get Current Location

	/**
	 * get address
	 * 
	 * @param context
	 * @return
	 */
	public String getAddress() {
		String currentLocation = "";
		Logger.debug("Location : " + mobileLocation);
		if (mobileLocation != null) {
			locManager.removeUpdates(locListener); // This needs to stop getting
													// the location data and
													// save the battery power.

			String googleMapAPI = Constants.GOOGLE_MAP_API;
			googleMapAPI = googleMapAPI + mobileLocation.getLatitude() + ","
					+ mobileLocation.getLongitude() + "&sensor=true";

			currentLocation = JsonParser.parserAddressByContent(HttpNetService
					.getDataByURL(googleMapAPI, null));
		} else {
			currentLocation = "";
		}

		return currentLocation;
	} // End get Address
}
